package com.idea.easy.log.publisher;

import com.idea.easy.log.provider.EasyLogInfoUtil;
import com.idea.easy.log.model.ErrorLogModel;
import com.idea.easy.log.provider.SpringAware;
import com.idea.easy.log.utils.ExceptionUtil;
import com.idea.easy.log.utils.WebUtil;
import org.springframework.context.ApplicationEvent;

import javax.servlet.http.HttpServletRequest;

/**
 * @className: ErrorLogPublisher
 * @description: 错误日志事件发布者
 * @author: salad
 * @date: 2022/6/3
 **/
public class ErrorLogPublisher extends LogPublisher {

    private final Throwable error;

    public ErrorLogPublisher(ApplicationEvent event,Throwable error) {
        this.error = error;
        setEvent(event);
    }

    public static ErrorLogPublisher event(ApplicationEvent event,Throwable error){
        return new ErrorLogPublisher(event,error);
    }


    @Override
    public void publish() {
        HttpServletRequest request = WebUtil.getRequest();
        ApplicationEvent event = getEvent();
        ErrorLogModel model = (ErrorLogModel)event.getSource();
            model.setStackInfo(ExceptionUtil.getStackTraceAsStr(error)); //堆栈信息
            model.setErrorName(error.getClass().getName());
            model.setErrorMessage(error.getMessage());
            StackTraceElement element = ExceptionUtil.getElement(error, 0);
            if (null != element){
                model.setMethodClass(element.getClassName());
                model.setMethodName(element.getMethodName());
                model.setErrorFileName(element.getFileName());
                model.setErrorLineNumber(element.getLineNumber());
            }
        EasyLogInfoUtil.appendRequestInfo(request,model);
        SpringAware.publishEvent(event);
    }
}
